<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.administrators') }}</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('administrators-add')" @click="addAdminOpen('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" border :data="list" max-height="700px" style="margin-top: 20px;">
        <el-table-column label="ID" prop="id" sortable="custom" width="60" />
        <el-table-column :label="$t('table.name')" prop="user_name" />
        <el-table-column :label="$t('table.tel')" prop="phone" />
        <el-table-column :label="$t('table.state')" prop="status">
          <template slot-scope="{row}">
            <el-tag :type="row.status|statusFilter">
              {{ row.status|formStatusData }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.roleName')" prop="group_name" />
        <el-table-column :label="$t('table.manipulator')" prop="operator_name" />
        <el-table-column :label="$t('table.lastLoginTime')" prop="login_at">
          <template slot-scope="{row}">
            {{ row.login_at|timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.creationTime')" prop="created_at">
          <template slot-scope="{row}">
            {{ row.created_at|timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="!checkPermission('administrators-edit')" @click="addAdminOpen('edit',row)">{{ $t('button.edit') }}</el-button>

            <el-button icon="el-icon-delete" type="dang er" size="mini" :disabled="!checkPermission('administrators-del')" @click="delUserAdmin(row.id)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
      </el-row>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" @opened="openDialog" @close="btnCanle">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="150px">
        <el-form-item :label="$t('table.name')">
          <el-input v-model="formData.user_name" :placeholder="$t('table.enterThe')+' '+$t('table.name')" style="width:50%" />
        </el-form-item>
        <el-form-item :label="$t('table.portrait')">
          <ImageUpload ref="staffPhoto" />
        </el-form-item>
        <el-form-item :label="$t('table.password')">
          <el-input v-model="formData.password" show-password :placeholder="$t('table.enterThe')+' '+$t('table.password')" style="width:50%" />
        </el-form-item>
        <el-form-item :label="$t('table.tel')">
          <el-input v-model="formData.phone" :placeholder="$t('table.enterThe')+' '+$t('table.tel')" style="width:50%" />
        </el-form-item>
        <el-form-item :label="$t('table.state')">
          <el-select v-model.number="formData.status" :placeholder="$t('table.selectThe')+' '+$t('table.state')">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.role')">
          <el-select v-model.number="formData.group_id" :placeholder="$t('table.selectThe')+' '+$t('table.role')">
            <el-option v-for="(item,index) in groupData" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getUserAdminList, getAdminGroupList, addUserAdmin, delUserAdmin } from '@/api/user'
import user from '@/store/modules/user'
import Cookie from 'js-cookie'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      languages: Cookie.get('language'),
      list: [],
      downloadLoading: false,
      statusData: [{
        id: 1,
        value: this.$t('table.normal')
      },
      {
        id: 2,
        value: this.$t('table.deactivate')
      }],
      query: {
        page: 1,
        limit: 10
      },
      count: 0,
      dialogTitle: this.$t('table.addadministrators'),
      groupData: [],
      groupCount: 0,
      formData: {
        id: undefined,
        aid: 38,
        user_name: '',
        user_pic: '',
        password: '',
        phone: '',
        status: undefined,
        group_id: undefined,
        is_show: 0,
        operator_uid: 0
      },
      rules: {
        user_name: [{ required: true, message: this.$t('table.name') + this.$t('prompt.noEmpty'), trigger: 'blur' }],
        phone: [{ required: true, message: this.$t('table.tel') + this.$t('prompt.noEmpty'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('table.state') + this.$t('prompt.noEmpty'), trigger: 'blur' }]
      },
      showDialog: false
    }
  },
  created() {
    // 获取userid
    this.formData.operator_uid = parseFloat(user.state.userId)
    this.getUserAdmin()
    this.getAdminGroup()
  },
  methods: {
    // 获取管理员列表
    async getUserAdmin() {
      this.downloadLoading = true
      const { count, list } = await getUserAdminList(this.query)
      this.list = list
      this.count = count
      this.downloadLoading = false
    },
    // 获取角色列表
    async getAdminGroup() {
      const data = {
        page: 1,
        limit: 1000
      }
      const { count, list } = await getAdminGroupList(data)
      this.groupData = list
      this.groupCount = count
    },
    // 点击展开新增修改
    addAdminOpen(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('table.addadministrators')
        this.formData.id = undefined
        this.formData.user_name = ''
        this.formData.user_pic = ''
        this.formData.password = ''
        this.formData.phone = ''
        this.formData.status = undefined
        this.formData.group_id = undefined
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = this.$t('table.editadministrators')
        this.formData.id = row.id
        this.formData.user_name = row.user_name
        this.formData.password = ''
        this.formData.phone = row.phone
        this.formData.status = row.status
        this.formData.group_id = row.group_id
        this.formData.user_pic = row.user_pic
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 点击确定时
    async btnOk() {
      try {
        // 校验整个表单
        await this.$refs.ruleForm.validate()
        // 读取上传组件的数据
        const fileList = this.$refs.staffPhoto.fileList
        // 循环判断是否已经完成全部上传
        if (fileList.some(item => !item.upload)) {
          //  如果此时去找 upload为false的图片 找到了说明 有图片还没有上传完成
          this.$message.warning(this.$t('prompt.noImage'))
          return
        }
        this.formData = { ...this.formData, user_pic: fileList && fileList.length ? fileList[0].url : '' }
        // 调用新增接口
        await addUserAdmin(this.formData)
        // 更新数据
        this.getUserAdmin()
        this.btnCanle()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 给图片赋值
    openDialog() {
      if (this.formData.user_pic) {
        this.$refs.staffPhoto.fileList = [{ url: this.formData.user_pic, upload: true }]
      }
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        id: undefined,
        user_name: '',
        user_pic: '',
        password: '',
        phone: '',
        status: undefined,
        group_id: undefined
      }
      this.$refs.staffPhoto.fileList = []
      this.$refs.ruleForm.clearValidate()// 重置校验结果
      this.showDialog = false
    },
    // 删除管理员
    async delUserAdmin(e) {
      const data = {
        id: e
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await delUserAdmin(data)
        this.getUserAdmin()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getUserAdmin()
    }
  }
})
</script>

